#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
	: QMainWindow(parent)
	, ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	show_networkcard();
	Multhread *capture_thread = new Multhread;
	// 捕获按钮是开启还是关闭
	static bool capture_button = false;
	connect(ui->actionrun_or_stop, &QAction::triggered,this,[=](){
		capture_button = !capture_button;
		if(capture_button)
		{
			int result = this->capture();
			// 判断捕获是否成功 并且文件文件描述符不为空
			if(result == 1 && device_file_descriptor)
			{
				capture_thread->set_device_file_descriptor(device_file_descriptor);
				capture_thread->set_flag();
				capture_thread->start();
				ui->actionrun_or_stop->setIcon(QIcon(":/images/stop.png"));
				ui->comboBox_network_card->setEnabled(false);
			}
		}
		else
		{
			capture_thread->reset_flag();
			// 结束释放资源
			capture_thread->quit();
			capture_thread->wait();
			ui->actionrun_or_stop->setIcon(QIcon(":/images/start.png"));
			ui->comboBox_network_card->setEnabled(true);
			pcap_close(device_file_descriptor);
			device_file_descriptor = nullptr;
		}
	});

	connect(capture_thread,&Multhread::send_data_package,this,&MainWindow::receive_data_package);
}

void MainWindow::show_networkcard()
{
	int result = pcap_findalldevs(&all_device,error_buffer);
	if(result == -1)
	{
		qDebug() << result << error_buffer;
	}
	else
	{
		for (current_device = all_device;current_device!=nullptr;current_device=current_device->next)
		{
			QString device_name = current_device->name;
			QString device_descriptor = current_device->description;
			ui->comboBox_network_card->addItem(device_name+device_descriptor);
		}
	}
}

MainWindow::~MainWindow()
{
	delete ui;
}

void MainWindow::on_comboBox_network_card_currentIndexChanged(int index)
{
	int i=0;
	current_device=all_device;
	while(i!=index)
	{
		current_device = current_device->next;
		i++;
	}
}
int MainWindow::capture()
{
	device_file_descriptor = pcap_open_live(current_device->name,65536,1,1000,error_buffer);
	if(!device_file_descriptor)
	{
		pcap_freealldevs(all_device);
		current_device = nullptr;
		return -1;
	}
	else
	{
		if(pcap_datalink(device_file_descriptor)!=DLT_EN10MB)
		{
			pcap_close(device_file_descriptor);
			pcap_freealldevs(all_device);
			current_device = nullptr;
			device_file_descriptor = nullptr;
		}
		statusBar()->showMessage(current_device->description);
	}
	return 1;
}
